/**
 * Created with JetBrains WebStorm.
 * User: rekey
 * Date: 7/9/13
 * Time: 21:14
 * To change this template use File | Settings | File Templates.
 */
var mongoose = require('mongoose');
var schemas = require('../schemas/index.js');
var schema = schemas['id'];
var when = require('when');

schema.statics.findAndModify = function(query, sort, doc, options, callback) {
    return this.collection.findAndModify(query, sort, doc, options, callback);
};

mongoose.model('id', schema);
var model = mongoose.model('id');

module.exports = {
    getID : function(name) {
        var deferred = when.defer();
        model.findAndModify({
            _id : name
        }, '', {
            $inc : {
                next : 1
            }
        }, {
            "new" : true,
            'upsert' : true
        }, function(err, doc) {
            if (err) {
                deferred.reject(err);
            } else {
                deferred.resolve(doc.next);
            }
        });
        return deferred.promise;
    },
    setPre : function(name, schema) {
        var that = this;
        schema.pre('save', function(next) {
            var Model = this;
            that.getID(name).then(function(id) {
                Model['_id'] = id;
                next();
            });
        });
    }
};